package net.assassin8.bautista.stalker;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.Toast;

public class MallStalkerActivity extends Activity {

	private static final String URI_PREFIX = "file:///sdcard/data/net.assassin8.bautista.stalker/";
	private static final String TAG = "MallStalkerActivity";
	private long mallId;
	private int floorNumber;
	private String floorPlanImage;
	private long floorPlanId;
	private int floorPlanWidth;
	private int floorPlanHeight;
	private long sessionId;
	private Stalker stalker;
	private Context ctx;

	private StalkerProvider sp = new StalkerProvider(this);
	private WebView webView;
	private int totalFloors;
	@SuppressWarnings("unused")
	private String mallName;

	protected void onSaveInstanceState(Bundle outState) {
		webView.saveState(outState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mall_stalker_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.stepBack:
			// Delete the previous trajectory from the DB

			webView.loadUrl("javascript:(function() { "
					+ "if(backPointX != null) {"
					+ "ctx.strokeStyle = '#fff'; ctx.lineWidth = 8;"
					+ "ctx.beginPath();"
					+ "ctx.moveTo(backPointX,backPointY);"
					+ "ctx.lineTo(previousPointX,previousPointY);"
					+ "ctx.stroke();ctx.closePath();"
					+ "previousPointX = backPointX; previousPointY = backPointY;"
					+ "}" + "})()");
			return true;
		case R.id.nextFloor:
			// Create an intent to go to itself
			if (floorNumber < totalFloors) {
				Intent i = new Intent(MallStalkerActivity.this,
						MallStalkerActivity.class);
				i.putExtra("MALL_ID", mallId);
				int nextFloorNumber = floorNumber + 1;
				i.putExtra("FLOOR_NUMBER", nextFloorNumber);
				i.putExtra("SESSION_ID", sessionId);
				MallStalkerActivity.this.startActivity(i);
				MallStalkerActivity.this.finish();
			} else {
				Toast.makeText(ctx, "This is the top floor", Toast.LENGTH_SHORT).show();
			}
			return true;
		case R.id.endSess:
			Intent endIntent = new Intent(MallStalkerActivity.this,
					EndSessionActivity.class);
			endIntent.putExtra("MALL_ID", mallId);
			MallStalkerActivity.this.startActivity(endIntent);
			MallStalkerActivity.this.finish();
			return true;
		case R.id.prevFloor:
			if (floorNumber > 1) {
				Intent i = new Intent(MallStalkerActivity.this,
						MallStalkerActivity.class);
				i.putExtra("MALL_ID", mallId);
				int nextFloorNumber = floorNumber - 1;
				i.putExtra("FLOOR_NUMBER", nextFloorNumber);
				i.putExtra("SESSION_ID", sessionId);
				MallStalkerActivity.this.startActivity(i);
				MallStalkerActivity.this.finish();
			} else {
				Toast.makeText(ctx, "This is the bottom floor", Toast.LENGTH_SHORT).show();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stalker_view);

		if (savedInstanceState != null)
			((WebView) findViewById(R.id.WebView01))
					.restoreState(savedInstanceState);

		webView = (WebView) findViewById(R.id.WebView01);
		webView.getSettings().setJavaScriptEnabled(true);

		stalker = ((Stalker) getApplicationContext());
		ctx = this;

		Bundle extras = getIntent().getExtras();

		mallId = extras.getLong("MALL_ID");
		floorNumber = extras.getInt("FLOOR_NUMBER");
		sessionId = extras.getLong("SESSION_ID");

		Log.i(TAG, "Mall ID is: " + mallId);
		Log.i(TAG, "Floor number is: " + floorNumber);

		sp.open();
		// Get the mall's details
		Cursor mall = sp.getMall(mallId);
		if (mall.moveToFirst()) {
			mallName = mall.getString(0);
			totalFloors = mall.getInt(1);
		}
		mall.close();

		// Get the floor plan
		Cursor fp = sp.getFloorPlan(mallId, floorNumber);
		if (fp.moveToFirst()) {
			floorPlanId = fp.getLong(0);
			floorPlanImage = fp.getString(1);
			floorPlanWidth = fp.getInt(2);
			floorPlanHeight = fp.getInt(3);
			Log.i(TAG, "Width: " + floorPlanWidth + "; Height: "
					+ floorPlanHeight);

		}
		fp.close();

		// Get the shops
		Cursor shops = sp.getShops(floorPlanId);

		// create interface
		JsInterface jsInterface = new JsInterface();

		// add interface
		webView.addJavascriptInterface(jsInterface, "android");
		
		String html = "<!DOCTYPE html><html>"
				+ "<head>"
				+ "<script type='text/javascript'>"
				+ "var previousPathX = null; var previousPathY = null;"
				+ "var previousPointX = null; var previousPointY = null;"
				+ "var backPointX = null; var backPointY = null;"
				+ "var shopRegions = new Array();"
				+ "var canvas = document.getElementById(\"canvas\");"
				+ "var ctx = canvas.getContext(\"2d\");"
				+ "function drawPathTrajectory(e) {"
				+ "ctx.strokeStyle='#f00'; ctx.lineWidth = 5; "
				+ "if(previousPointX == null || previousPointY == null) {"
				+ "previousPointX = e.pageX; previousPointY = e.pageY;"
				+ "ctx.arc(previousPointX,previousPointY,10,0,2*Math.PI,false);"
				+ "ctx.fillStyle='#8ED6FF';" 
				+ "ctx.fill();"
				+ "ctx.lineWidth=5;" 
				+ "ctx.strokeStyle='black';"
				+ "ctx.stroke();" 
				+ "} else {"
				+ "ctx.beginPath();"
				+ "ctx.moveTo(previousPointX,previousPointY); "
				+ "ctx.lineTo(e.pageX,e.pageY); ctx.stroke(); ctx.closePath();"
				+ "backPointX = previousPointX; backPointY = previousPointY;"
				+ "previousPointX = e.pageX; previousPointY = e.pageY;" 
				+ "}"
				+ "android.savePathTrajectory(previousPointX,previousPointY);"
				+ "}" 
				+ "function draw() {"
				+ "canvas = document.getElementById(\"canvas\");"
				+ "ctx = canvas.getContext(\"2d\");";

		int startX, startY, width, height, i;
		@SuppressWarnings("unused")
		String shopName;
		if (shops.moveToFirst()) {
			for(i=0;i<shops.getCount();i++) {
				shops.moveToPosition(i);
				startX = shops.getInt(4);
				startY = shops.getInt(5);
				width = (shops.getInt(6) - shops.getInt(4));
				height = (shops.getInt(7) - shops.getInt(5));
				shopName = shops.getString(1);

				html += "ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';"
						+ "ctx.fillRect (" + startX + ", " + startY + ", " + width
						+ ", " + height + ");";

				Log.i(TAG, "shop found");
			}
		}
		shops.close();

		html += "}"
				+ "function drawPath(pathX,pathY) {"
				+ "if(previousPathX == null || previousPathY == null) {"
				+ "previousPathX = pathX+5; previousPathY = pathY+5;"
				+ "} else {"
				+ "ctx.strokeStyle = '#f00';"
				+ "ctx.lineWidth = 1;"
				+ "ctx.beginPath(); ctx.moveTo(previousPathX,previousPathY);"
				+ "ctx.lineTo(pathX+5,pathY+5);"
				+ "ctx.stroke(); ctx.closePath();"
				+ "previousPathX = pathX+5; previousPathY = pathY+5;"
				+ "}"
				+ "}"
				+ "</script></head>"
				+ "<body style='width:"
				+ floorPlanWidth
				+ "px; height:"
				+ floorPlanHeight
				+ "px; background-image:url("
				+ URI_PREFIX
				+ floorPlanImage
				+ "); margin:0;' onload='draw()'><canvas id='canvas' width='"
				+ floorPlanWidth
				+ "' height='"
				+ floorPlanHeight
				+ "' style='position: absolute; top:0; z-index: 100;' onclick='drawPathTrajectory(event)'></canvas>";

		// Close the provider
		sp.close();

		html += "</body></html>";
		webView.loadDataWithBaseURL(URI_PREFIX, html, "text/html", "utf-8", "");
	}

	private class JsInterface {
		@SuppressWarnings("unused")
		public void showAlert(String x, String y) {
			stalker.alert(ctx, "x: " + x + " y: " + y);
		}

		@SuppressWarnings("unused")
		public void savePathTrajectory(long x, long y) {
			sp.open();
			sp.insertSessionTrajectory(sessionId, floorPlanId, x, y);
			sp.close();
		}
	}

	@Override
	public void onBackPressed() {
		// Do nothing
	}
}
